﻿#region Usings

using System;
using System.IO;
using System.IO.IsolatedStorage;

#endregion

namespace SilverBox.Extensions
{
    public static class CachingExtensions
    {
        public static void Save(this object obj, string fileName)
        {
            Save(obj, fileName, CacheType.App);
        }

        public static void Save(this object obj, string fileName, CacheType type)
        {
            IsolatedStorageFile store;
            switch (type)
            {
                case CacheType.Site:
                    store = IsolatedStorageFile.GetUserStoreForSite();
                    break;
                case CacheType.App:
                    store = IsolatedStorageFile.GetUserStoreForApplication();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("type");
            }
            var stream = store.OpenFile(fileName,
                                        FileMode.OpenOrCreate,
                                        FileAccess.Write);
            stream.WriteAllText(obj.SerializeToJsonString());
        }

        public static T Open<T>(this string obj)
        {
            return Open<T>(obj, CacheType.App);
        }

        public static T Open<T>(this string obj, CacheType type)
        {
            IsolatedStorageFile store;
            switch (type)
            {
                case CacheType.Site:
                    store = IsolatedStorageFile.GetUserStoreForSite();
                    break;
                case CacheType.App:
                    store = IsolatedStorageFile.GetUserStoreForApplication();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("type");
            }
            var stream = store.OpenFile(obj,
                                        FileMode.OpenOrCreate,
                                        FileAccess.Read);
            return stream.ReadAllText().DeserializeFromJson<T>();
        }
    }

    public enum CacheType
    {
        Site,
        App
    }
}